package com.shop.controller;


import com.shop.entity.User;
import com.shop.service.CartService;
import com.shop.service.UserService;
import com.shop.service.util.JwtUtil;
import com.shop.service.vo.CartVo;
import com.shop.util.CookieUtils;
import com.shop.util.UserTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author D
 * @since 2023-03-11 03:02:04
 */
@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 修改购物车中指定商品的数量
     * @param productId 商品ID
     * @param request HTTP请求对象
     * @param count 商品数量
     * @return 修改后的购物车信息
     */
    @RequestMapping("/changeCart")
    public CartVo changeCart(Integer productId, HttpServletRequest request, Integer count) {
        User user = UserTokenUtil.getUser(request,userService);
        return cartService.changeCart(productId,user.getId(),count);
    }
    /**
     * 获取当前用户的购物车中的商品列表
     * @param request HTTP请求对象
     * @return 包含购物车商品信息的列表
     */
    @RequestMapping("/listItems")
    public List<CartVo> listItems(HttpServletRequest request){
        User user = UserTokenUtil.getUser(request,userService);
        List<Object> values = redisTemplate.opsForHash().values(user.getId().toString());
        return values.stream().map(o -> (CartVo) o).collect(Collectors.toList());
    }
    /**
     * 计算购物车中指定商品的总价
     * @param productIds 商品ID数组
     * @param request HTTP请求对象
     * @return 指定商品的总价
     */
    @RequestMapping("/calculateTotal")
    public BigDecimal calculateTotal(@RequestParam(value = "productIds[]")Integer[] productIds,HttpServletRequest request) {
        User user = UserTokenUtil.getUser(request,userService);
        return cartService.calculateTotal(user.getId(), productIds);
    }

}

